import axios, { AxiosResponse } from 'axios';
import { User, LoginRequest, RegisterRequest, Video, UpdateProfileRequest, LiveStream, Comment } from '../types';

// API响应类型
interface ApiResponse<T> {
  success: boolean;
  data?: T;
  message?: string;
  error?: string;
}

interface LoginResponse {
  token: string;
  user: User;
}

interface RegisterResponse {
  token: string;
  user: User;
}

const api = axios.create({
  baseURL: 'http://localhost:8080/api',
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 用户认证相关API
export const authAPI = {
  // 用户登录
  login: async (credentials: LoginRequest): Promise<LoginResponse> => {
    try {
      const response = await api.post<ApiResponse<LoginResponse>>('/users/login', credentials);
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '登录失败，请重试');
    }
  },

  // 用户注册
  register: async (userData: RegisterRequest): Promise<RegisterResponse> => {
    try {
      const response = await api.post<ApiResponse<RegisterResponse>>('/users/register', userData);
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '注册失败，请重试');
    }
  },

  // 获取当前用户信息
  getCurrentUser: async (userId: number): Promise<User> => {
    try {
      const response = await api.get<ApiResponse<User>>(`/users/me?userId=${userId}`);
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '获取用户信息失败');
    }
  },

  // 更新用户信息
  updateProfile: async (userData: UpdateProfileRequest): Promise<User> => {
    try {
      const formData = new FormData();
      
      if (userData.username) {
        formData.append('username', userData.username);
      }
      if (userData.bio) {
        formData.append('bio', userData.bio);
      }
      if (userData.avatar) {
        formData.append('avatar', userData.avatar);
      }

      const response = await api.put<ApiResponse<User>>('/users/profile', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '更新用户信息失败');
    }
  },

  // 上传头像
  uploadAvatar: async (file: File, userId: number): Promise<{ avatarUrl: string; user: User }> => {
    try {
      const formData = new FormData();
      formData.append('avatar', file);
      formData.append('userId', userId.toString());

      const response = await api.post<ApiResponse<{ avatarUrl: string; user: User }>>('/users/uploadAvatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '头像上传失败');
    }
  },
};

// 视频相关API
export const videoAPI = {
  // 获取所有视频
  getVideos: async (): Promise<Video[]> => {
    try {
      const response = await api.get<ApiResponse<Video[]>>('/videos');
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '获取视频列表失败');
    }
  },

  // 获取单个视频
  getVideo: async (id: number): Promise<Video> => {
    try {
      const response = await api.get<ApiResponse<Video>>(`/videos/${id}`);
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '获取视频失败');
    }
  },

  // 上传视频
  uploadVideo: async (videoFile: File, thumbnailFile: File | null, title: string, description: string, userId: number): Promise<Video> => {
    try {
      const formData = new FormData();
      formData.append('video', videoFile);
      if (thumbnailFile) {
        formData.append('thumbnail', thumbnailFile);
      }
      formData.append('title', title);
      formData.append('description', description);
      formData.append('userId', userId.toString());

      const response = await api.post<ApiResponse<Video>>('/videos/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '视频上传失败');
    }
  },

  // 点赞/取消点赞视频
  toggleLike: async (videoId: number, userId: number): Promise<{ video: Video; isLiked: boolean }> => {
    try {
      const response = await api.post<ApiResponse<Video>>(`/videos/${videoId}/like?userId=${userId}`);
      const isLikedResponse = await api.get<{ success: boolean; isLiked: boolean }>(`/videos/${videoId}/like/check?userId=${userId}`);
      return {
        video: response.data.data!,
        isLiked: isLikedResponse.data.isLiked
      };
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '操作失败');
    }
  },

  // 检查用户是否已点赞视频
  checkLikeStatus: async (videoId: number, userId: number): Promise<boolean> => {
    try {
      const response = await api.get<{ success: boolean; isLiked: boolean; message?: string }>(`/videos/${videoId}/like/check?userId=${userId}`);
      return response.data.isLiked;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '检查点赞状态失败');
    }
  },

  // 添加评论
  addComment: async (videoId: number, userId: number, content: string): Promise<Comment> => {
    try {
      const response = await api.post<{ success: boolean; data: Comment; message?: string }>(`/videos/${videoId}/comments?userId=${userId}&content=${encodeURIComponent(content)}`);
      return response.data.data;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '评论失败');
    }
  },

  // 获取视频评论
  getComments: async (videoId: number): Promise<{ comments: Comment[]; count: number }> => {
    try {
      const response = await api.get<{ success: boolean; data: Comment[]; count: number; message?: string }>(`/videos/${videoId}/comments`);
      return {
        comments: response.data.data,
        count: response.data.count
      };
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '获取评论失败');
    }
  },

  // 删除评论
  deleteComment: async (commentId: number, userId: number): Promise<void> => {
    try {
      await api.delete(`/videos/comments/${commentId}?userId=${userId}`);
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '删除评论失败');
    }
  },
};

// 关注相关API
export const followAPI = {
  // 关注用户
  followUser: async (followerId: number, followingId: number): Promise<void> => {
    try {
      await api.post('/follows/follow', null, {
        params: { followerId, followingId }
      });
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '关注失败');
    }
  },

  // 取消关注用户
  unfollowUser: async (followerId: number, followingId: number): Promise<void> => {
    try {
      await api.post('/follows/unfollow', null, {
        params: { followerId, followingId }
      });
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '取消关注失败');
    }
  },

  // 检查是否已关注
  checkFollowStatus: async (followerId: number, followingId: number): Promise<boolean> => {
    try {
      const response = await api.get<{ success: boolean; isFollowing: boolean; message?: string }>('/follows/check', {
        params: { followerId, followingId }
      });
      return response.data.isFollowing;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '检查关注状态失败');
    }
  },

  // 获取关注列表
  getFollowing: async (userId: number): Promise<User[]> => {
    try {
      const response = await api.get<ApiResponse<User[]>>(`/follows/following/${userId}`);
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '获取关注列表失败');
    }
  },

  // 获取粉丝列表
  getFollowers: async (userId: number): Promise<User[]> => {
    try {
      const response = await api.get<ApiResponse<User[]>>(`/follows/followers/${userId}`);
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '获取粉丝列表失败');
    }
  },

  // 获取关注数量
  getFollowingCount: async (userId: number): Promise<number> => {
    try {
      const response = await api.get<ApiResponse<{ count: number }>>(`/follows/following-count/${userId}`);
      return response.data.data!.count;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '获取关注数量失败');
    }
  },

  // 获取粉丝数量
  getFollowersCount: async (userId: number): Promise<number> => {
    try {
      const response = await api.get<ApiResponse<{ count: number }>>(`/follows/followers-count/${userId}`);
      return response.data.data!.count;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '获取粉丝数量失败');
    }
  },
};

export const liveStreamAPI = {
  createLiveStream: async (title: string, description: string, userId: number): Promise<LiveStream> => {
    try {
      const response = await api.post<ApiResponse<LiveStream>>('/live/create', { title, description, userId });
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '创建直播失败');
    }
  },
  startLiveStream: async (streamId: number, userId: number): Promise<LiveStream> => {
    try {
      const response = await api.post<ApiResponse<LiveStream>>(`/live/${streamId}/start?userId=${userId}`);
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '开始直播失败');
    }
  },
  endLiveStream: async (streamId: number, userId: number): Promise<LiveStream> => {
    try {
      const response = await api.post<ApiResponse<LiveStream>>(`/live/${streamId}/end?userId=${userId}`);
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '结束直播失败');
    }
  },
  getLiveStreams: async (): Promise<LiveStream[]> => {
    try {
      const response = await api.get<ApiResponse<LiveStream[]>>('/live');
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '获取直播列表失败');
    }
  },
  getLiveStreamById: async (streamId: number): Promise<LiveStream> => {
    try {
      const response = await api.get<ApiResponse<LiveStream>>(`/live/${streamId}`);
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '获取直播信息失败');
    }
  },
  getLiveStreamByKey: async (streamKey: string): Promise<LiveStream> => {
    try {
      const response = await api.get<ApiResponse<LiveStream>>(`/live/key/${streamKey}`);
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '获取直播信息失败');
    }
  },
  getUserLiveStreams: async (userId: number): Promise<LiveStream[]> => {
    try {
      const response = await api.get<ApiResponse<LiveStream[]>>(`/live/user/${userId}`);
      return response.data.data!;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '获取用户直播列表失败');
    }
  },
  likeLiveStream: async (streamId: number): Promise<void> => {
    try {
      await api.post(`/live/${streamId}/like`);
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '点赞直播失败');
    }
  },
  deleteLiveStream: async (streamId: number, userId: number): Promise<void> => {
    try {
      await api.delete(`/live/${streamId}?userId=${userId}`);
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '删除直播失败');
    }
  },
};

export { api }; 